{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-08-28T09:05:20.606616Z",
     "start_time": "2024-08-28T09:05:19.042677Z"
    }
   },
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "from torch.nn import functional as F\n",
    "from d2l import torch as d2l\n",
    "\n",
    "batch_size, num_steps = 32, 35\n",
    "train_iter, vocab = d2l.load_data_time_machine(batch_size, num_steps)"
   ],
   "execution_count": 1,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 1. 定义模型",
   "id": "4b5209f92a138f04"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T09:05:51.249893Z",
     "start_time": "2024-08-28T09:05:51.235597Z"
    }
   },
   "cell_type": "code",
   "source": [
    "num_hiddens = 256\n",
    "rnn_layer = nn.RNN(len(vocab), num_hiddens)"
   ],
   "id": "e18dd7fd2a55a99e",
   "execution_count": 2,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "使用张量来初始化隐状态,它的形状是（隐藏层数，批量大小，隐藏单元数）",
   "id": "ab356bde223645fe"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T09:06:32.283392Z",
     "start_time": "2024-08-28T09:06:32.273351Z"
    }
   },
   "cell_type": "code",
   "source": [
    "state = torch.zeros((1, batch_size, num_hiddens))\n",
    "state.shape"
   ],
   "id": "5363db2a03bde2ae",
   "execution_count": 3,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T09:12:44.090787Z",
     "start_time": "2024-08-28T09:12:44.055523Z"
    }
   },
   "cell_type": "code",
   "source": [
    "X = torch.rand(size=(num_steps, batch_size, len(vocab)))\n",
    "Y, state_new = rnn_layer(X, state)\n",
    "\n",
    "print(Y.shape)\n",
    "print(state_new.shape)"
   ],
   "id": "6ec9df5f7cd96284",
   "execution_count": 4,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "为一个完整的循环神经网络模型定义了一个`RNNModel`类",
   "id": "51d261109150e12e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T09:16:43.863886Z",
     "start_time": "2024-08-28T09:16:43.844586Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#@save\n",
    "class RNNModel(nn.Module):\n",
    "    \"\"\"循环神经网络模型\"\"\"\n",
    "\n",
    "    def __init__(self, rnn_layer, vocab_size, **kwargs):\n",
    "        super(RNNModel, self).__init__(**kwargs)\n",
    "        self.rnn = rnn_layer\n",
    "        self.vocab_size = vocab_size\n",
    "        self.num_hiddens = self.rnn.hidden_size\n",
    "\n",
    "        # 如果RNN是双向的（之后将介绍），num_directions应该是2，否则应该是1\n",
    "        if not self.rnn.bidirectional:\n",
    "            self.num_directions = 1\n",
    "\n",
    "            # 自定义输出层\n",
    "            self.linear = nn.Linear(self.num_hiddens, self.vocab_size)\n",
    "\n",
    "        else:\n",
    "            self.num_directions = 2\n",
    "            self.linear = nn.Linear(self.num_hiddens * 2, self.vocab_size)\n",
    "\n",
    "    def forward(self, inputs, state):\n",
    "        X = F.one_hot(inputs.T.long(), self.vocab_size)\n",
    "        X = X.to(torch.float32)\n",
    "        Y, state = self.rnn(X, state)\n",
    "        # 全连接层首先将Y的形状改为(时间步数*批量大小,隐藏单元数)\n",
    "        # 它的输出形状是(时间步数*批量大小,词表大小)\n",
    "        output = self.linear(Y.reshape((-1, Y.shape[-1])))\n",
    "        return output, state\n",
    "\n",
    "    def begin_state(self, device, batch_size=1):\n",
    "        if not isinstance(self.rnn, nn.LSTM):\n",
    "            # nn.GRU以张量作为隐状态\n",
    "            return torch.zeros((self.num_directions * self.rnn.num_layers,\n",
    "                                batch_size, self.num_hiddens),\n",
    "                               device=device)\n",
    "        else:\n",
    "            # nn.LSTM以元组作为隐状态\n",
    "            return (torch.zeros((\n",
    "                self.num_directions * self.rnn.num_layers,\n",
    "                batch_size, self.num_hiddens), device=device),\n",
    "                    torch.zeros((\n",
    "                        self.num_directions * self.rnn.num_layers,\n",
    "                        batch_size, self.num_hiddens), device=device))"
   ],
   "id": "bb7046d6286ad17",
   "execution_count": 5,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 2. 训练与预测",
   "id": "ccdbc574343e33d6"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "训练前：基于一个具有随机权重的模型进行预测",
   "id": "42a3931722adb466"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T09:18:21.461854Z",
     "start_time": "2024-08-28T09:18:21.388497Z"
    }
   },
   "cell_type": "code",
   "source": [
    "device = d2l.try_gpu()\n",
    "\n",
    "net = RNNModel(rnn_layer, vocab_size=len(vocab))\n",
    "\n",
    "net = net.to(device)\n",
    "\n",
    "d2l.predict_ch8('time traveller', 10, net, vocab, device)"
   ],
   "id": "c97176d5440d636d",
   "execution_count": 6,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "训练：定义的超参数调用`train_ch8`，并且使用高级API训练模型",
   "id": "7b3e253bebe5e7e4"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "num_epochs, lr = 500, 1\n",
    "d2l.train_ch8(net, train_iter, vocab, lr, num_epochs, device)"
   ],
   "id": "e63238971de1b626",
   "execution_count": 7,
   "outputs": []
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-08-28T09:20:34.301464Z",
     "start_time": "2024-08-28T09:20:34.285669Z"
    }
   },
   "cell_type": "code",
   "source": [
    "predict = lambda prefix: d2l.predict_ch8(prefix, 50, net, vocab, d2l.try_gpu())\n",
    "print(predict('time traveller'))"
   ],
   "id": "2a411d459910008a",
   "execution_count": 8,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "code",
   "execution_count": null,
   "source": "",
   "id": "d5c1aecf200845d2",
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
